package com.vv.tools.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FileUtils {

    private FileUtils() {
    }

    public static File getClassPathFile(String resourceLocation) {
        if (resourceLocation.startsWith("classpath:")) {
            String path = resourceLocation.substring("classpath:".length());
            File file = new File(getFilePath() + path);
            if (!file.exists()) {
                return null;
            }
            return file;
        } else {
            File file = new File(getFilePath() + resourceLocation);
            if (!file.exists()) {
                return null;
            }
            return file;
        }
    }

    public static String read(String filePath) {
        return read(Objects.requireNonNull(getClassPathFile(filePath)));
    }


    public static String read(File file) {
        long len = file.length();
        if (len >= 2147483647L) {
            log.error("File is larger then max array size");
            return null;
        } else {
            byte[] bytes = new byte[(int) len];
            try (FileInputStream in = new FileInputStream(file)) {
                int readLength = in.read(bytes);
                if (readLength < len) {
                    log.error("File length is [{}] but read [{}]!", len, readLength);
                    return null;
                }
            } catch (Exception var10) {
                log.error(var10.getMessage());
                return null;
            }
            return new String(bytes, StandardCharsets.UTF_8);
        }
    }

    public static void write(File file, String str) {
        try (FileWriter fileWriter = new FileWriter(file);) {
            fileWriter.write(str);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    private static String getFilePath() {
        URL location = FileUtils.class.getProtectionDomain().getCodeSource().getLocation();
        String filePath = URLDecoder.decode(location.getPath(), StandardCharsets.UTF_8);
        if (filePath.startsWith("nested:/")) {
            filePath = filePath.substring("nested:/".length());
        }
        if (filePath.startsWith("root")) {
            filePath = "/" + filePath;
        }
        if (filePath.contains(".jar")) {
            filePath = filePath.substring(0, filePath.lastIndexOf("vv-tools-0.0.1-SNAPSHOT.jar"));
        }
        log.info("filePath: {}", filePath);
        return filePath;
    }

}
